package com.mall.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mall.shop.constants.MallConstrant;
import com.mall.shop.entity.product.Category;
import com.mall.shop.mapper.CategoryMapper;
import com.mall.shop.service.CategoryService;
import org.springframework.stereotype.Service;

;import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 商品三级分类(Category)表服务实现类
 *
 * @author 龙茶清欢
 * @since 2023-01-16 15:32:39
 */
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Override
    public List<Category> findListWithTree() {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getShowStatus, MallConstrant.SHOWSTATUS);
        List<Category> categories = this.baseMapper.selectList(queryWrapper);

        return categories.stream()
                .filter(category -> category.getParentCid() == 0)
                .peek(category -> category.setChildren(getChildren(category, categories)))
                .sorted(Comparator.comparingInt(Category::getSort))
                .collect(Collectors.toList());
    }

    // 查询子分类
    private List<Category> getChildren(Category category, List<Category> categories) {
        return categories.stream()
                .filter(item -> Objects.equals(item.getParentCid(), category.getCatId()))
                .peek(item -> item.setChildren(getChildren(item, categories)))
                // 使用Comparator进行排序时，要避免排序字段数据库数据出现空值从而导致空指针
                .sorted(Comparator.comparingInt(Category::getSort))
                .collect(Collectors.toList());
    }
}

